<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta
      name="description"
      content="Agentic Trading Simulator UI for configuring and visualizing trading bot simulations."
    />
    <title>Agentic Trading Simulator</title>
    <script
      src="https://cdn.plot.ly/plotly-3.0.1.min.js"
      charset="utf-8"
    ></script>
    <link rel="stylesheet" href="/static/style.css" />
  </head>
  <body>
    <div class="container">
      <h1>📈 Agentic Trading Simulator</h1>
      <div class="disclaimer-message">
        <strong>Disclaimer:</strong> This application is for informational and
        educational purposes only. It does not constitute financial, investment,
        or trading advice. Use at your own risk.
      </div>
      <div class="content-wrapper">
        <div class="sidebar">
          <h2>⚙️ Configuration</h2>
          <form id="sim-form" action="/run_simulation" method="post">
            <h3>🤖 AlphaBot Agent</h3>
            <label for="alphabot_short_sma">Short SMA Period:</label>
            <input
              title="The number of days for the shorter Simple Moving Average (SMA). Used with the long SMA to generate buy/sell signals."
              type="range"
              id="alphabot_short_sma"
              name="alphabot_short_sma"
              min="1"
              max="50"
              value="{{ params.alphabot_short_sma | default(DEFAULT_ALPHABOT_SHORT_SMA) }}"
              oninput="this.nextElementSibling.value = this.value"
            />
            <output
              >{{ params.alphabot_short_sma |
              default(DEFAULT_ALPHABOT_SHORT_SMA) }}</output
            ><br />

            <label for="alphabot_long_sma">Long SMA Period:</label>
            <input
              title="The number of days for the longer Simple Moving Average (SMA). Used with the short SMA to generate buy/sell signals."
              type="range"
              id="alphabot_long_sma"
              name="alphabot_long_sma"
              min="1"
              max="100"
              value="{{ params.alphabot_long_sma | default(DEFAULT_ALPHABOT_LONG_SMA) }}"
              oninput="this.nextElementSibling.value = this.value"
            />
            <output
              >{{ params.alphabot_long_sma | default(DEFAULT_ALPHABOT_LONG_SMA)
              }}</output
            ><br />

            <label for="alphabot_trade_qty">Trade Quantity:</label>
            <input
              title="The number of shares to buy or sell in each transaction triggered by the AlphaBot."
              type="number"
              id="alphabot_trade_qty"
              name="alphabot_trade_qty"
              min="1"
              step="1"
              value="{{ params.alphabot_trade_qty | default(DEFAULT_ALPHABOT_TRADE_QTY) }}"
            /><br />

            <label for="alphabot_url">AlphaBot Service URL:</label>
            <input
              title="The URL where the AlphaBot A2A (Agent-to-Agent) service is running."
              type="text"
              id="alphabot_url"
              name="alphabot_url"
              value="{{ params.alphabot_url | default(DEFAULT_ALPHABOT_URL) }}"
            /><br />

            <h3>🛡️ RiskGuard Agent</h3>

            <label for="riskguard_max_pos_size">Max Position Size ($):</label>
            <input
              title="Maximum allowed value ($) for a single trade."
              type="number"
              id="riskguard_max_pos_size"
              name="riskguard_max_pos_size"
              min="1000"
              step="1000"
              value="{{ params.riskguard_max_pos_size | default(DEFAULT_RISKGUARD_MAX_POS_SIZE) }}"
            /><br />

            <label for="riskguard_max_concentration"
              >Max Concentration (%):</label
            >
            <input
              title="Maximum allowed percentage of total portfolio value held in a single asset."
              type="range"
              id="riskguard_max_concentration"
              name="riskguard_max_concentration"
              min="0"
              max="100"
              step="1"
              value="{{ params.riskguard_max_concentration | default((DEFAULT_RISKGUARD_MAX_CONCENTRATION * 100)|int) }}"
              oninput="this.nextElementSibling.value = this.value"
            />
            <output
              >{{ params.riskguard_max_concentration |
              default((DEFAULT_RISKGUARD_MAX_CONCENTRATION * 100)|int)
              }}</output
            ><br />

            <label for="riskguard_url">RiskGuard Service URL:</label>
            <input
              title="The URL where the RiskGuard A2A (Agent-to-Agent) service is running."
              type="text"
              id="riskguard_url"
              name="riskguard_url"
              value="{{ params.riskguard_url | default(DEFAULT_RISKGUARD_URL) }}"
            /><br />
            <br /><br />

            <h3>📈 Simulator Parameters</h3>
            <label for="sim_days">Simulation Days:</label>
            <input
              title="The total number of trading days the simulation will run for."
              type="range"
              id="sim_days"
              name="sim_days"
              min="10"
              max="500"
              value="{{ params.sim_days | default(DEFAULT_SIM_DAYS) }}"
              oninput="this.nextElementSibling.value = this.value"
            />
            <output>{{ params.sim_days | default(DEFAULT_SIM_DAYS) }}</output
            ><br />

            <label for="sim_initial_cash">Initial Cash ($):</label>
            <input
              title="The starting amount of cash available in the portfolio at the beginning of the simulation."
              type="number"
              id="sim_initial_cash"
              name="sim_initial_cash"
              min="1000"
              step="1000"
              value="{{ params.sim_initial_cash | default(DEFAULT_SIM_INITIAL_CASH) }}"
            /><br />

            <label for="sim_initial_price">Initial Price ($):</label>
            <input
              title="The starting price of the simulated asset at the beginning of the simulation."
              type="number"
              id="sim_initial_price"
              name="sim_initial_price"
              min="1"
              step="1"
              value="{{ params.sim_initial_price | default(DEFAULT_SIM_INITIAL_PRICE) }}"
            /><br />

            <label for="sim_volatility">Volatility (Std Dev):</label>
            <input
              title="The standard deviation of the daily price changes, representing market volatility. Higher values mean more price fluctuation."
              type="range"
              id="sim_volatility"
              name="sim_volatility"
              min="0.005"
              max="0.1"
              step="0.001"
              value="{{ params.sim_volatility | default(DEFAULT_SIM_VOLATILITY) }}"
              oninput="this.nextElementSibling.value = this.value"
            />
            <output
              >{{ params.sim_volatility | default(DEFAULT_SIM_VOLATILITY)
              }}</output
            ><br />

            <label for="sim_trend">Trend (Daily Drift):</label>
            <input
              title="The average daily percentage change (drift) in the asset price. Positive values indicate an upward trend, negative values a downward trend."
              type="range"
              id="sim_trend"
              name="sim_trend"
              min="-0.005"
              max="0.005"
              step="0.0001"
              value="{{ params.sim_trend | default(DEFAULT_SIM_TREND) }}"
              oninput="this.nextElementSibling.value = this.value"
            />
            <output>{{ params.sim_trend | default(DEFAULT_SIM_TREND) }}</output
            ><br />

            <button type="submit">🚀 Run Simulation</button>
          </form>
          <p class="info-note">
            Ensure both A2A services (RiskGuard and AlphaBot) are running before
            starting.
          </p>
        </div>

        <div class="main-content">
          <h2>📊 Simulation Results</h2>

          {% if status.message %}
          <div class="status-message {% if status.is_error %}error{% endif %}">
            {{ status.message }}
          </div>
          {% endif %} {% if status.results and status.results.final_portfolio %}
          <div class="results-grid">
            <div class="metric">
              <h4>Total Value</h4>
              <p>
                {{ status.results.final_portfolio.total_value | format_currency
                }}
              </p>
            </div>
            <div class="metric">
              <h4>Cash</h4>
              <p>{{ status.results.final_portfolio.cash | format_currency }}</p>
            </div>
            <div class="metric">
              <h4>Shares Held</h4>
              <p>{{ status.results.final_portfolio.shares }}</p>
            </div>
            <div class="metric">
              <h4>Holdings Value</h4>
              <p>
                {{ status.results.final_portfolio.holdings_value |
                format_currency }}
              </p>
            </div>
          </div>
          {% endif %} {% if status.results %}
          <h3>📊 Simulation Charts</h3>
          {% if status.results.charts and
          status.results.charts.combined_chart_json %}
          <div id="chart-combined"></div>
          {% else %}
          <p>Combined chart data not available for this run.</p>
          {% endif %}

          <h3>📜 Trade Signals & Execution Log</h3>
          <textarea id="trade_signals_log" name="trade_signals_log" readonly>
{{ status.results.signals_log | default('No signals generated.') }}</textarea
          >

          {% else %} {% if status.message != "Simulation started..." %}
          <p>Configure parameters and click "Run Simulation" to see results.</p>
          {% endif %} {% endif %}
        </div>
      </div>
    </div>

    <script>
      const combinedChartDiv = document.getElementById('chart-combined');

      {% if status.results and status.results.charts and status.results.charts.combined_chart_json %}
      if (combinedChartDiv) {
        try {
          const combinedSpec = {{ status.results.charts.combined_chart_json | safe }};
          Plotly.newPlot(combinedChartDiv, combinedSpec.data, combinedSpec.layout);
          Plotly.Plots.resize(combinedChartDiv);
        } catch (e) {
          console.error("Error rendering chart:", e);
          combinedChartDiv.innerHTML = "<p>Error rendering chart.</p>";
        }
      } else {
          console.warn("Chart div ('chart-combined') not found in DOM.");
      }
      {% endif %}


      const form = document.getElementById("sim-form");
      form.addEventListener("submit", () => {
        const button = form.querySelector('button[type="submit"]');
          button.disabled = true;
          button.textContent = "Running...";
        });
    </script>
    <footer>
      Made with ❤️ using
      <a
        href="https://google.github.io/adk-docs/"
        target="_blank"
        rel="noopener noreferrer"
        >ADK</a
      >
      and
      <a
        href="https://google.github.io/A2A/#/"
        target="_blank"
        rel="noopener noreferrer"
        >A2A</a
      >.
    </footer>
  </body>
</html>
